/**  
 * Project Name:api-webhook  
 * File Name:ChsiService.java  
 * Package Name:com.example.service.webhook.business.chsi.service  
 * Date:2016年7月26日下午4:07:19  
 * Copyright (c) 2016, yuandong@51dojo.com All Rights Reserved.  
 *  
*/

package com.example.service.webhook.business.jingdong.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.example.service.webhook.business.jingdong.api.JingdongClient;
import com.example.service.webhook.business.jingdong.billitem.JdBillTask;
import com.example.service.webhook.business.jingdong.dto.JdDeliverAddress;
import com.example.service.webhook.business.jingdong.dto.JdProductInfo;
import com.example.service.webhook.business.jingdong.dto.JdTradeDetails;
import com.example.service.webhook.business.jingdong.dto.JdTradeDetailsRes;
import com.example.service.webhook.business.jingdong.dto.JdUserInfo;
import com.example.service.webhook.business.jingdong.dto.JdWealth;
import com.example.service.webhook.business.jingdong.entity.JdDeliverAddressEntity;
import com.example.service.webhook.business.jingdong.entity.JdProductInfoEntity;
import com.example.service.webhook.business.jingdong.entity.JdTradeDetailsEntity;
import com.example.service.webhook.business.jingdong.entity.JdUserInfoEntity;
import com.example.service.webhook.business.jingdong.entity.JdWealthEntity;
import com.example.service.webhook.business.jingdong.repository.JdDeliverAddressRepository;
import com.example.service.webhook.business.jingdong.repository.JdProductInfoRepository;
import com.example.service.webhook.business.jingdong.repository.JdTradeInfoRepository;
import com.example.service.webhook.business.jingdong.repository.JdUserInfoRepository;
import com.example.service.webhook.business.jingdong.repository.JdWealthRepository;

/**
 * JingdongService <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2016年7月26日 下午4:07:19 <br/>
 * 
 * @author yuandong
 * @version
 * @since JDK 1.6
 * @see
 */
@Service
public class JingdongService {

	private static final Logger LOGGER = LoggerFactory.getLogger(JingdongService.class);

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;
	@Autowired
	private JingdongClient jingdongClient;
	@Autowired
	private JdUserInfoRepository jdUserInfoRepository;
	@Autowired
	private JdDeliverAddressRepository jdDeliverAddressRepository;
	@Autowired
	private JdWealthRepository jdWealthRepository;
	@Autowired
	private JdTradeInfoRepository jdTradeInfoRepository;
	@Autowired
	private JdProductInfoRepository jdProductInfoRepository;

	/**
	 * 
	 * fetchBill:处理京东回调 <br/>
	 * 在收到魔蝎的邮箱账单回调时执行<br/>
	 * 基本信息<br/>
	 * 收货地址<br/>
	 * 收货地址<br/>
	 * 
	 * @author yuandong
	 * @param task
	 * @since JDK 1.6
	 */
	public void fetchBill(final JdBillTask task) {

		// 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
		// 超时会导致魔蝎数据进行重试，会收到重复的回调请求

		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				saveUserInfo(task);
				saveDeliverAddress(task);
				saveWealth(task);
				saveTradeDetails(task);

			}
		}

		);

	}

	private void saveUserInfo(JdBillTask task) {
		try {
			JdUserInfo userinfo = jingdongClient.getUserInfo(task.getTaskId());
			if (userinfo != null) {
				JdUserInfoEntity jingdongUserInfoEntity = new JdUserInfoEntity();
				BeanUtils.copyProperties(userinfo, jingdongUserInfoEntity);
				jingdongUserInfoEntity.setUserId(task.getUserId());
				JdUserInfoEntity isExistEntity = jdUserInfoRepository.getUserInfo(task.getUserId(),
						task.getMappingId());
				if (isExistEntity != null) {
					jingdongUserInfoEntity.setCreateTime(isExistEntity.getCreateTime());
					jingdongUserInfoEntity.setId(isExistEntity.getId());
					jdUserInfoRepository.updateUserInfo(jingdongUserInfoEntity);
				} else {
					jdUserInfoRepository.saveUserInfo(jingdongUserInfoEntity);
				}
			}
		} catch (Exception e) {
			LOGGER.error("处理京东客户基本信息出现异常", e);
		}

	}

	private void saveDeliverAddress(JdBillTask task) {
		try {
			jdDeliverAddressRepository.deleteDeliverAddress(task.getUserId(), task.getMappingId());
			loadDeliverAddressByCallApi(task.getTaskId(), task.getUserId());
		} catch (Exception e) {
			LOGGER.error("saveDeliverAddress error", e);
		}
	}

	private void loadDeliverAddressByCallApi(String taskId, String userId) throws Exception {
		List<JdDeliverAddress> deliverAddressList = jingdongClient.getDeliverAddress(taskId);
		if (deliverAddressList != null && !deliverAddressList.isEmpty()) {
			for (JdDeliverAddress deliverAddress : deliverAddressList) {
				JdDeliverAddressEntity basicEntity = new JdDeliverAddressEntity();
				BeanUtils.copyProperties(deliverAddress, basicEntity);
				basicEntity.setUserId(userId);
				jdDeliverAddressRepository.saveDeliverAddress(basicEntity);
			}
		}
	}

	private void saveWealth(JdBillTask task) {
		try {
			JdWealth jdWealth = jingdongClient.getWealth(task.getTaskId());
			if (jdWealth != null) {
				JdWealthEntity jdWealthEntity = new JdWealthEntity();
				BeanUtils.copyProperties(jdWealth, jdWealthEntity);
				jdWealthEntity.setUserId(task.getUserId());
				JdWealthEntity isExistEntity = jdWealthRepository.getWealth(task.getUserId(), task.getMappingId());
				if (isExistEntity != null) {
					jdWealthEntity.setCreateTime(isExistEntity.getCreateTime());
					jdWealthEntity.setId(isExistEntity.getId());
					jdWealthRepository.updateWealth(jdWealthEntity);
				} else {
					jdWealthRepository.saveWealth(jdWealthEntity);
				}
			}
		} catch (Exception e) {
			LOGGER.error("处理京东资产状况出现异常", e);
		}

	}

	private void saveTradeDetails(JdBillTask task) {
		int page = 1;
		int pageSize = 200;
		try {

			do {
				JdTradeDetailsRes tradeDetailsRes = jingdongClient.getTradeDetailsRes(task.getTaskId(), page, pageSize);
				if (tradeDetailsRes != null && tradeDetailsRes.getSize() > 0) {
					pageSize = tradeDetailsRes.getSize();
					List<JdTradeDetails> tradeDetailsList = tradeDetailsRes.getTradedetails();
					for (JdTradeDetails tradeDetails : tradeDetailsList) {
						JdTradeDetailsEntity tradeDetailEntity = new JdTradeDetailsEntity();
						BeanUtils.copyProperties(tradeDetails, tradeDetailEntity);
						tradeDetailEntity.setUserId(task.getUserId());

						// 保存消费记录
						JdTradeDetailsEntity isExist = jdTradeInfoRepository.getTradeDetailEntity(task.getUserId(),
								task.getMappingId(), tradeDetails.getTradeId());
						if (isExist == null) {
							jdTradeInfoRepository.saveTradeDetail(tradeDetailEntity);
						} else {
							tradeDetailEntity.setId(isExist.getId());
							tradeDetailEntity.setCreateTime(isExist.getCreateTime());
							jdTradeInfoRepository.updateTradeDetail(tradeDetailEntity);
						}

						// 保存商品信息
						List<JdProductInfo> subOrders = tradeDetails.getProducts();
						if (subOrders != null && !subOrders.isEmpty()) {
							jdProductInfoRepository.deleteProductInfo(task.getUserId(), tradeDetails.getMappingId(),
									tradeDetails.getTradeId());
							for (JdProductInfo jdProductInfo : subOrders) {
								JdProductInfoEntity jdProductInfoEntity = new JdProductInfoEntity();
								BeanUtils.copyProperties(jdProductInfo, jdProductInfoEntity);
								jdProductInfoEntity.setUserId(task.getUserId());
								jdProductInfoRepository.saveProductInfo(jdProductInfoEntity);
							}
						}

					}
				} else {
					pageSize = 0;
				}
				page++;
			} while (pageSize == 200);
		} catch (Exception e) {
			LOGGER.error("saveTradeDetails error", e);
		}
	}

}
